/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package doghost.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.beansbinding.Converter;

/**
 *
 * @author duo
 */
public class CustomFormattedDateConverter extends Converter {

    protected String dateMask;

    public CustomFormattedDateConverter() {
        super();
        this.setDateMask("dd/MM/yyyy");
    }

    /**
     * Get the value of dateMask
     *
     * @return the value of dateMask
     */
    public String getDateMask() {
        return dateMask;
    }

    /**
     * Set the value of dateMask
     *
     * @param dateMask new value of dateMask
     */
    public void setDateMask(String dateMask) {
        this.dateMask = dateMask;
    }

    @Override
    public Object convertForward(Object value) {
        // Date para String
        if ((Date) value != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.getDateMask());
            simpleDateFormat.setLenient(false);
            return simpleDateFormat.format((Date) value);
        } else {
            return (String) null;
        }
    }

    @Override
    public Object convertReverse(Object value) {
        // String para Date
        String dateString = (String) value;
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Texto da " +
                "data a ser convertida: <" +
                (dateString == null ? "NULL" : dateString)  + ">");
        if(dateString.startsWith("99")) {
            Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Convertida para (Date) null");
            return (Date) null;
        } else {
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.getDateMask());
                simpleDateFormat.setLenient(false);
                Date date = simpleDateFormat.parse(dateString);
                return date;
            } catch (ParseException e) {
                if (this.getDateMask().length() == 10) {
                    return "  /  /    ";
                } else {
                    return "  /  /       :  ";
                }
            }
        }
    }
}
